package com.ymatou.iapi.tradingsettlement.testcase;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymatou.iapi.tradingsettlement.parameter.CommissionDetailReq;
import com.ymatou.iapi.tradingsettlement.service.CommissionDetailCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.HunterCallService;
import com.ymttest.business.service.PayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceHunterOrderCallService;
import com.ymttest.database.model.hunter.HunterSettlement;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sqlwapper.hunter.HunterSettlementWrapper;
import com.ymttest.utils.DataUtil;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.YMTDateUtil;

@Ignore
public class Ts_CommissionDetail {

	private static CommissionDetailReq commissionDetailReq;
	private static CommissionDetailCall commissionDetailCall;
	
	private static long userId = Long.valueOf(EnvSetup.getData("BuyUserId"));
	HunterSettlementWrapper hunterSettlementWrapper = new HunterSettlementWrapper();

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("推手销售佣金明细");
	}

	@Before
	public void caseUp() {
		commissionDetailReq = new CommissionDetailReq();
		commissionDetailCall = new CommissionDetailCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(commissionDetailCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	public void verifyDb(JSONArray object) throws JSONException,
			ClientProtocolException, IOException {

		//获得大礼包或普通商品的佣金
		List<HunterSettlement> hunterSettlementList = hunterSettlementWrapper
				.selectByHunterId(commissionDetailReq.getHunterId()).stream().filter(hunterSettlement -> hunterSettlement
						.getSettlement_type() == 20 || hunterSettlement
						.getSettlement_type() == 22).collect(Collectors.toList());
		String settlementStatus = "SETTLED";

		for (int i = 0; i < hunterSettlementList.size(); i++) {

			HunterSettlement actualObject = hunterSettlementList.get(i);

			if (actualObject.getSettlement_status() != 1)
				settlementStatus = "NOT_SETTLED";
			else if (actualObject.getSettlement_status() == 1)
				settlementStatus = "SETTLED";

			JSONObject expectobject = object.getJSONObject(i);

			DataUtil.verifyEquals(expectobject.getLong("orderId"),
					actualObject.getOrder_id(), "验证orderId");
			DataUtil.verifyDateEquals(expectobject.getString("paidTime"),
					actualObject.getPaid_time(), "验证paidTime");
			DataUtil.verifyEquals(expectobject.getString("settlementStatus"),
					settlementStatus, "验证settlementStatus");
			DataUtil.verifyEquals(
					new BigDecimal(expectobject.optString("totalAmount"))
							.setScale(2), actualObject.getTotal_amount(),
					"验证totalAmount");
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_001() {
		Logger.start(true, "查询推手当月未结算的大礼包数据");
		try {

			Logger.comment("前置数据准备");

			OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
			List<OrderPo> orderList = orderShardingWapper
					.selectHunterGiftBagOrderbyUserId(userId);

			if (orderList.size() > 0) {
				for (OrderPo po : orderList) {
					TradingCallService.cancelOrder(po.getOrderId(),
							CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
				}
			}

			// 生成一个新的推手
			Long serviverId = HunterCallService.buildHunterRelation(2, 1, 0)
					.get(0);

			// 推手为servicer
			TradingServiceResp serviverPlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 1);

			PayGateWayCallService
					.notifyCall(
							"13",
							TradingCallService.payOrder(userId,
									BigDecimal.ZERO,
									serviverPlaceOrder.getTradingId(), "13")
									.toString(),
							serviverPlaceOrder.getPayableAmount()
									.subtract(BigDecimal.ZERO).toString(),
							(int) userId);
			TradingSyncService.getSyncResult(serviverPlaceOrder.getOrderList()
					.get(0).getOrderId());

			Logger.comment("前置数据结束");

			commissionDetailReq.setHunterId(serviverId);
			commissionDetailReq.setYear(YMTDateUtil
					.getCurrentYearMonthDate("year"));
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			verifyDb(commissionDetailCall.getResult());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_002() {
		Logger.start(true, "查询推手当月未结算的普通商品数据");
		try {

			Logger.comment("前置数据准备");

			OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
			List<OrderPo> orderList = orderShardingWapper
					.selectHunterGiftBagOrderbyUserId(userId);

			if (orderList.size() > 0) {
				for (OrderPo po : orderList) {
					TradingCallService.cancelOrder(po.getOrderId(),
							CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
				}
			}

			// 生成一个新的推手
			Long serviverId = HunterCallService.buildHunterRelation(2, 1, 0)
					.get(0);

			// 推手为servicer
			TradingServiceResp serviverPlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 2);

			PayGateWayCallService
					.notifyCall(
							"13",
							TradingCallService.payOrder(userId,
									BigDecimal.ZERO,
									serviverPlaceOrder.getTradingId(), "13")
									.toString(),
							serviverPlaceOrder.getPayableAmount()
									.subtract(BigDecimal.ZERO).toString(),
							(int) userId);

			TradingSyncService.getSyncResult(serviverPlaceOrder.getOrderList()
					.get(0).getOrderId());

			Thread.sleep(5000);

			Logger.comment("前置数据结束");

			commissionDetailReq.setHunterId(serviverId);
			commissionDetailReq.setYear(YMTDateUtil
					.getCurrentYearMonthDate("year"));
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			verifyDb(commissionDetailCall.getResult());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_003() {
		Logger.start(true, "查询推手当月已结算的大礼包数据");
		try {

			Logger.comment("前置数据准备");

			OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
			List<OrderPo> orderList = orderShardingWapper
					.selectHunterGiftBagOrderbyUserId(userId);

			if (orderList.size() > 0) {
				for (OrderPo po : orderList) {
					TradingCallService.cancelOrder(po.getOrderId(),
							CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
				}
			}

			// 生成一个新的推手
			Long serviverId = HunterCallService.buildHunterRelation(2, 1, 0)
					.get(0);

			// 推手为servicer
			TradingServiceResp serviverPlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 1);

			long servicerOrderId = serviverPlaceOrder.getOrderList().get(0)
					.getOrderId();
			long servicerSellerId = serviverPlaceOrder.getOrderList().get(0)
					.getSellerId();

			PayGateWayCallService
					.notifyCall(
							"13",
							TradingCallService.payOrder(userId,
									BigDecimal.ZERO,
									serviverPlaceOrder.getTradingId(), "13")
									.toString(),
							serviverPlaceOrder.getPayableAmount()
									.subtract(BigDecimal.ZERO).toString(),
							(int) userId);
			TradingSyncService.getSyncResult(servicerOrderId);

			// 拼邮国际段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(servicerOrderId);
			// 拼邮国内段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 3);
			// 确认收货
			TradingCallService.confirmReceive(userId, servicerOrderId);

			Thread.sleep(5000);

			// 做结算
			hunterSettlementWrapper.updateExpectSettlementTimeByOrderId(
					YMTDateUtil.getBeforeOrNextDate(-1), servicerOrderId);
			HunterCallService.doCommissionSettlement();

			Logger.comment("前置数据结束");

			commissionDetailReq.setHunterId(serviverId);
			commissionDetailReq.setYear(YMTDateUtil
					.getCurrentYearMonthDate("year"));
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			verifyDb(commissionDetailCall.getResult());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_004() {
		Logger.start(true, "查询推手当月已结算的普通商品数据");
		try {

			Logger.comment("前置数据准备");

			OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
			List<OrderPo> orderList = orderShardingWapper
					.selectHunterGiftBagOrderbyUserId(userId);

			if (orderList.size() > 0) {
				for (OrderPo po : orderList) {
					TradingCallService.cancelOrder(po.getOrderId(),
							CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
				}
			}

			// 生成一个新的推手
			Long serviverId = HunterCallService.buildHunterRelation(2, 1, 0)
					.get(0);

			// 推手为servicer
			TradingServiceResp serviverPlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 2);
			long servicerOrderId = serviverPlaceOrder.getOrderList().get(0)
					.getOrderId();
			long servicerSellerId = serviverPlaceOrder.getOrderList().get(0)
					.getSellerId();

			PayGateWayCallService
					.notifyCall(
							"13",
							TradingCallService.payOrder(userId,
									BigDecimal.ZERO,
									serviverPlaceOrder.getTradingId(), "13")
									.toString(),
							serviverPlaceOrder.getPayableAmount()
									.subtract(BigDecimal.ZERO).toString(),
							(int) userId);
			TradingSyncService.getSyncResult(serviverPlaceOrder.getOrderList()
					.get(0).getOrderId());

			// 拼邮国际段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(servicerOrderId);
			// 拼邮国内段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 3);
			// 确认收货
			TradingCallService.confirmReceive(userId, servicerOrderId);

			Thread.sleep(5000);

			// 做结算
			hunterSettlementWrapper.updateExpectSettlementTimeByOrderId(
					YMTDateUtil.getBeforeOrNextDate(-1), serviverPlaceOrder
							.getOrderList().get(0).getOrderId());
			HunterCallService.doCommissionSettlement();

			Logger.comment("前置数据结束");

			commissionDetailReq.setHunterId(serviverId);
			commissionDetailReq.setYear(YMTDateUtil
					.getCurrentYearMonthDate("year"));
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			verifyDb(commissionDetailCall.getResult());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_005() {
		Logger.start(true, "查询推手当月已结算或未结算的多条数据");
		try {

			Logger.comment("前置数据准备");

			OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
			List<OrderPo> orderList = orderShardingWapper
					.selectHunterGiftBagOrderbyUserId(userId);

			if (orderList.size() > 0) {
				for (OrderPo po : orderList) {
					TradingCallService.cancelOrder(po.getOrderId(),
							CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
				}
			}

			// 生成一个新的推手
			Long serviverId = HunterCallService.buildHunterRelation(2, 1, 0)
					.get(0);

			Logger.comment("生成一个未结算的大礼包订单（开始）");
			TradingServiceResp giftPackagePlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 1);

			PayGateWayCallService.notifyCall(
					"13",
					TradingCallService.payOrder(userId, BigDecimal.ZERO,
							giftPackagePlaceOrder.getTradingId(), "13")
							.toString(), giftPackagePlaceOrder
							.getPayableAmount().subtract(BigDecimal.ZERO)
							.toString(), (int) userId);
			
			TradingSyncService.getSyncResult(giftPackagePlaceOrder
					.getOrderList().get(0).getOrderId());
			Logger.comment("生成一个未结算的大礼包订单（结束）");

			Logger.comment("生成一个已经结算的普通商品订单（开始）");
			// 推手为servicer
			TradingServiceResp serviverPlaceOrder = TradingPlaceHunterOrderCallService
					.placeHunterOrder(serviverId, userId, 2);
			long servicerOrderId = serviverPlaceOrder.getOrderList().get(0)
					.getOrderId();
			long servicerSellerId = serviverPlaceOrder.getOrderList().get(0)
					.getSellerId();

			PayGateWayCallService
					.notifyCall(
							"13",
							TradingCallService.payOrder(userId,
									BigDecimal.ZERO,
									serviverPlaceOrder.getTradingId(), "13")
									.toString(),
							serviverPlaceOrder.getPayableAmount()
									.subtract(BigDecimal.ZERO).toString(),
							(int) userId);

			TradingSyncService.getSyncResult(serviverPlaceOrder.getOrderList()
					.get(0).getOrderId());

			// 拼邮国际段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(servicerOrderId);
			// 拼邮国内段发货
			TradingCallService.delivery(servicerSellerId, servicerOrderId,
					LogisticsTypeEnum.OVERSEAS_DELIVERY, 3);
			// 确认收货
			TradingCallService.confirmReceive(userId, servicerOrderId);

			Thread.sleep(5000);

			// 做结算
			hunterSettlementWrapper.updateExpectSettlementTimeByOrderId(
					YMTDateUtil.getBeforeOrNextDate(-1), servicerOrderId);
			HunterCallService.doCommissionSettlement();
			Logger.comment("生成一个已经结算的普通商品订单（结束）");

			Logger.comment("前置数据结束");

			commissionDetailReq.setHunterId(serviverId);
			commissionDetailReq.setYear(YMTDateUtil
					.getCurrentYearMonthDate("year"));
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			verifyDb(commissionDetailCall.getResult());

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_006() {
		Logger.start(true, "年份小于2018");
		try {

			commissionDetailReq.setHunterId(11047305000L);
			commissionDetailReq.setYear(2017);
			commissionDetailReq.setMonth(YMTDateUtil
					.getCurrentYearMonthDate("month"));
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			DataUtil.verifyEquals(400, commissionDetailCall.getResponseData()
					.getInt("code"), "验证code");
			DataUtil.verifyEquals(100, commissionDetailCall.getResponseData()
					.getInt("bcode"), "验证bcode");
			DataUtil.verifyEquals("year:年份不能小于2018年", commissionDetailCall
					.getResponseData().getString("msg"), "验证msg");
			DataUtil.verifyEquals(false, commissionDetailCall.getResponseData()
					.getJSONObject("data").getBoolean("success"), "验证success");
			DataUtil.verifyEquals("ILLEGAL_ARGUMENT",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorCode"),
					"验证errorCode");
			DataUtil.verifyEquals("year:年份不能小于2018年",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorMessage"),
					"验证errorMessage");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_007() {
		Logger.start(true, "月份必须在1至12月之前");
		try {

			commissionDetailReq.setHunterId(11047305000L);
			commissionDetailReq.setYear(2018);
			commissionDetailReq.setMonth(13);
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			DataUtil.verifyEquals(400, commissionDetailCall.getResponseData()
					.getInt("code"), "验证code");
			DataUtil.verifyEquals(100, commissionDetailCall.getResponseData()
					.getInt("bcode"), "验证bcode");
			DataUtil.verifyEquals("month:月份必须在1至12月之前", commissionDetailCall
					.getResponseData().getString("msg"), "验证msg");
			DataUtil.verifyEquals(false, commissionDetailCall.getResponseData()
					.getJSONObject("data").getBoolean("success"), "验证success");
			DataUtil.verifyEquals("ILLEGAL_ARGUMENT",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorCode"),
					"验证errorCode");
			DataUtil.verifyEquals("month:月份必须在1至12月之前",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorMessage"),
					"验证errorMessage");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_008() {
		Logger.start(true, "推手id为空");
		try {

			commissionDetailReq.setHunterId(0);
			commissionDetailReq.setYear(2018);
			commissionDetailReq.setMonth(12);
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			DataUtil.verifyEquals(400, commissionDetailCall.getResponseData()
					.getInt("code"), "验证code");
			DataUtil.verifyEquals(100, commissionDetailCall.getResponseData()
					.getInt("bcode"), "验证bcode");
			DataUtil.verifyEquals("hunterId:推手id不能为空", commissionDetailCall
					.getResponseData().getString("msg"), "验证msg");
			DataUtil.verifyEquals(false, commissionDetailCall.getResponseData()
					.getJSONObject("data").getBoolean("success"), "验证success");
			DataUtil.verifyEquals("ILLEGAL_ARGUMENT",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorCode"),
					"验证errorCode");
			DataUtil.verifyEquals("hunterId:推手id不能为空",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorMessage"),
					"验证errorMessage");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_009() {
		Logger.start(true, "推手在该月没有数据");
		try {

			commissionDetailReq.setHunterId(1);
			commissionDetailReq.setYear(2018);
			commissionDetailReq.setMonth(12);
			commissionDetailReq.setPageIndex(1);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			DataUtil.verifyEquals(200, commissionDetailCall.getResponseData()
					.getInt("code"), "验证code");
			DataUtil.verifyEquals(0, commissionDetailCall.getResponseData()
					.getInt("bcode"), "验证bcode");
			DataUtil.verifyEquals(true, commissionDetailCall.getResponseData()
					.getJSONObject("data").getBoolean("success"), "验证success");
			DataUtil.verifyEquals(null,
					commissionDetailCall.getResult(),
					"验证results");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_CommissionDetail_010() {
		Logger.start(true, "pageIndex为空");
		try {

			commissionDetailReq.setHunterId(11047305000L);
			commissionDetailReq.setYear(2018);
			commissionDetailReq.setMonth(12);
			commissionDetailReq.setPageIndex(0);
			commissionDetailReq.setPageSize(10);

			commissionDetailCall.setData(commissionDetailReq);
			commissionDetailCall.callService();

			DataUtil.verifyEquals(500, commissionDetailCall.getResponseData()
					.getInt("code"), "验证code");
			DataUtil.verifyEquals(199, commissionDetailCall.getResponseData()
					.getInt("bcode"), "验证bcode");
			DataUtil.verifyEquals("系统繁忙，请稍后重试", commissionDetailCall
					.getResponseData().getString("msg"), "验证msg");
			DataUtil.verifyEquals(false, commissionDetailCall.getResponseData()
					.getJSONObject("data").getBoolean("success"), "验证success");
			DataUtil.verifyEquals("UNKNOWN",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorCode"),
					"验证errorCode");
			DataUtil.verifyEquals("系统繁忙，请稍后重试",
					commissionDetailCall.getResponseData()
							.getJSONObject("data").getString("errorMessage"),
					"验证errorMessage");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
